<!--
 * @Author: White
 * @description: 写文章
 * @LastEditTime: 2021-08-12 17:46:24
-->

<template>
  <div class="main">
    <el-form class="ruleForm" label-width="100px">
      <el-form-item label="标题">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="内容">
        <el-input :rows="10" type="textarea" v-model="form.content"></el-input>
      </el-form-item>
      <el-form-item label="作者">
        <el-input v-model="form.author"></el-input>
      </el-form-item>
      <el-form-item label="封面预览图">
        <input type="file" name="file" class="up-add" @change="getFile($event,'file')"/>
      </el-form-item>
      <el-form-item class="submit">
        <el-button type="primary" @click="submit()">立即创建</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { useRouter } from 'vue-router'
import { ElNotification } from 'element-plus'
import { defineComponent, reactive, toRefs } from 'vue'
import { auth, app } from '@/api/clouldbase'
export default defineComponent({
  setup () {
    const router = useRouter()
    const data = reactive({
      form: {
        author: '',
        title: '',
        content: '',
        time: '',
        cover: ''
      }
    })
    const submit = () => {
      data.form.time = new Date()
      auth
        .anonymousAuthProvider()
        .signIn()
        .then(() => {
          const db = app.database()
          db.collection('nav_content').add(data.form).then(res => {
            okmessage()
            data.form = {
              author: '',
              title: '',
              content: '',
              time: '',
              cover: ''
            }
            setTimeout(() => {
              router.push({
                path: 'DetailArticle',
                query: { id: res.id }
              })
            }, 3000)
          })
        })
        .catch(err => {
          console.log(err)
        })
    }
    const okmessage = () => {
      ElNotification({
        title: '成功',
        message: '添加成功，3秒后前往预览！',
        type: 'success'
      })
    }
    const getFile = (e) => {
      var files = e.target.files
      app.uploadFile({
        // 云存储的路径
        cloudPath: `images/${files[0].name}`,
        // 需要上传的文件，File 类型
        filePath: files[0]
      }).then(res => {
        data.form.cover = res.download_url
      })
    }
    return {
      ...toRefs(data),
      submit,
      getFile,
      okmessage
    }
  }
})
</script>

<style lang="scss" scoped>
.main {
  max-width: 1200px;
  height: calc(100vh - 16px);
  background-color: #fff;
  margin: 0 auto;
  .ruleForm {
    padding-top: 30px;
    .submit {
      text-align: center !important;
    }
  }
}
</style>
